package com.chenfan.filestore.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/** @author lizj */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
  @Override
  protected Object determineCurrentLookupKey() {
    String s = DynamicDataSourceContextHolder.get();
    log.info("正在操作数据源ID：{}", s);
    return s;
  }

  /**
   * 动态更新自定义数据源
   * @param customDataSources
   */
  public void updateTargetDataSource(DataSource defaultDataSource, Map<String, DataSource> customDataSources){
    Map<Object,Object> customDS = new HashMap<>(16);
    customDS.putAll(customDataSources);
    setDefaultTargetDataSource(defaultDataSource);
    setTargetDataSources(customDS);
    afterPropertiesSet();
  }
}
